import { useEffect, useRef, useState } from 'react';

import BaiIcon from '@/assets/bai.png';
import ActiveBg from '@/assets/p-active.png';
import DefaultBg from '@/assets/p-default.png';
import { useInViewport } from 'ahooks';
import useCustomNumberFont from './useCustomNumberFont';

export default function useProgress(props: { start: number; end: number }) {
  const ref = useRef<HTMLDivElement>(null);

  const { renderNode: renderNodeCustomFontNode } = useCustomNumberFont();
  const [_inViewport, ratio] = useInViewport(ref, {
    threshold: [0, 0.25, 0.5, 0.75, 1],
  });

  useEffect(() => {
    if (ratio && ratio >= 1) autoStart();
  }, [ratio]);

  const [progress, setProgress] = useState<number>(props.start);
  const t = useRef<NodeJS.Timeout>();

  function autoStart() {
    t.current = setInterval(() => {
      setProgress((v) => (v += 1));
    }, 20);
  }

  useEffect(() => {
    if (progress >= props.end) {
      setProgress(props.end);
      clearInterval(t.current);
    }
  }, [progress]);

  function renderNode() {
    return (
      <div className=" flex items-center text-white" ref={ref}>
        <div
          className="w-[462px] h-[66px] bg-full flex-1"
          style={{
            backgroundImage: `url(${DefaultBg})`,
          }}
        >
          <i
            className=" block h-full bg-no-repeat bg-left bg-[length:462px_66px]"
            style={{
              width: `${progress}%`,
              backgroundImage: `url(${ActiveBg})`,
            }}
          ></i>
        </div>

        <div className="flex items-end ml-3">
          {renderNodeCustomFontNode({ value: progress })}
          <span
            className="w-[40px] h-[40px] -mb-[6px] inline-block bg-cover bg-no-repeat"
            style={{
              backgroundImage: `url(${BaiIcon})`,
              backgroundSize: '100% auto',
            }}
          ></span>
        </div>
      </div>
    );
  }
  return {
    renderNode,
  };
}

